package com.ruoyi.web.controller.guomao;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IFileUploadService;
import com.ruoyi.system.service.IGmParkRateService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 停车费Controller
 *
 * @author cwl
 * @date 2021-12-07
 */
@Controller
@RequestMapping("/guomao/parkRate")
public class GmParkRateController extends BaseController {
    private String prefix = "propertys/guomao/parkRate";
    @Autowired
    private IGmParkRateService gmParkRateService;
    //    文件传输
    @Autowired
    private IFileUploadService fileUploadService;

    @GetMapping()
    public String ParkRate(ModelMap modelMap)
    {
        return prefix + "/main";
    }
    /**
     * 查询停车费
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ParkRate parkRate)
    {
        startPage();
        List<ParkRate> list = gmParkRateService.selectParkRateList(parkRate);
        for (ParkRate pr:list) {
            Integer count = fileUploadService.getFileCountByKey(pr.getParkId());
            pr.setFileCount(count);
        }
        return getDataTable(list);
    }


    /**
     * 新增停车费信息
     */
    @GetMapping("/add")
    public String add(ModelMap modelMap)
    {
        return prefix + "/add";
    }

    /**
     * 新增保存停车费信息
     */
    @Log(title = "停车费", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ParkRate parkRate)
    {
        return toAjax(gmParkRateService.insertParkRate(parkRate));
    }

    /**
     * 修改停车费信息
     */
    @GetMapping("/edit/{parkId}")
    public String edit(@PathVariable("parkId") String parkId, ModelMap mmap)
    {
        ParkRate parkRate = gmParkRateService.selectParkRateById(parkId);
        mmap.put("parkRate", parkRate);
        return prefix + "/edit";
    }

    /**
     * 修改保存停车费信息
     */
//    @RequiresPermissions("guomao:parkRate:edit")
    @Log(title = "停车费信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ParkRate parkRate)
    {
        return toAjax(gmParkRateService.updateParkRate(parkRate));
    }

    /**
     * 删除停车费信息
     */
    @Log(title = "停车费信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String[] ids)
    {
        return toAjax(gmParkRateService.deleteParkRateByIds(ids));
    }

    /**
     * 导入停车列表
     * */
    @Log(title = "停车费", businessType = BusinessType.IMPORT)
//    @RequiresPermissions("guomao:parkRate:import")
    @PostMapping("/importExcel")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ParkRate> util = new ExcelUtil<>(ParkRate.class);
        List<ParkRate> lists = util.importExcel(file.getInputStream());
        SysUser sysUser = ShiroUtils.getSysUser();
        //校验数据
        String res = gmParkRateService.validateDatas(lists);
        if (StringUtils.isNotBlank(res)){
            return AjaxResult.error(res);
        }
        String message =gmParkRateService.importRelations(lists,updateSupport,sysUser);
        return AjaxResult.success(message);
    }

    /**
     * 导入中的下载模板
     * */
//    @RequiresPermissions("guomao:parkRate:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<ParkRate> util = new ExcelUtil<ParkRate>(ParkRate.class);
        return util.importTemplateExcel("停车信息");
    }

    /**
     * 导出停车费列表
     */
//    @RequiresPermissions("guomao:parkRate:export")
    @Log(title = "停车费", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ParkRate parkRate,String ids)
    {
        List<ParkRate> list = new ArrayList<>();
        if(StringUtils.isNotEmpty(ids)){
            String[] parkIds = Convert.toStrArray(ids);
            for(String parkId:parkIds){
                ParkRate thisParkRate = gmParkRateService.selectParkRateById(parkId);
                list.add(thisParkRate);
            }
        }else {
            list = gmParkRateService.selectParkRateList(parkRate);
        }

        ExcelUtil<ParkRate> util = new ExcelUtil<ParkRate>(ParkRate.class);
        return util.exportExcel(list, "parkRate");
    }


    /**
     * 跳转上传页面
     */
    @GetMapping("/toUpload/{parkId}")
    public String toUpload(@PathVariable String parkId, ModelMap modelMap) {
        List<FileUploadInfo> fileUploadInfoList = fileUploadService.getFileUploadListByKey(parkId);
        modelMap.put("parkId",parkId);
        modelMap.put("fileInfos",fileUploadInfoList);
        return prefix + "/parkUpload";
    }

    /**
     * 上传文件
     */
    @PostMapping("/Upload")
    @ResponseBody
    public AjaxResult parkUpload(MultipartFile file)
    {
        String filePath = "";
        try {
            filePath = FileUploadUtils.upload(Global.getGmParkRatePath(),file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return AjaxResult.success(file.getOriginalFilename(),filePath);
    }

    /**
     * 保存文件地址到库里
     */
    @PostMapping("/changePath")
    @ResponseBody
    public AjaxResult changePath(String parkId,String filePath,String fileName) {
        try{
            FileUploadInfo fileUploadInfo = new FileUploadInfo();
            fileUploadInfo.setFileId(UUID.randomUUID().toString().replaceAll("-",""));
            fileUploadInfo.setFileName(fileName);
            fileUploadInfo.setFilePath(filePath);
            fileUploadInfo.setFileType("2");  //
            fileUploadInfo.setStatus("1");  //有效
            fileUploadInfo.setBelongKey(parkId);
            fileUploadService.insertFileUpload(fileUploadInfo);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 将文件置为失效
     */
    @PostMapping("/removeAnnex")
    @ResponseBody
    public AjaxResult removeAnnex(String key) {
        //String InfoId,String filePath    目前用不上
        try{
            fileUploadService.deleteFile(key);
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error("文件删除失败");
        }
        return AjaxResult.success();
    }

    /**
     * 下载文件到指定目录
     */
    @PostMapping("/downloadInfo")
    @ResponseBody
    public AjaxResult downloadInfo(String parkId) {
        List<FileUploadInfo> fileUploadInfos = fileUploadService.getFileUploadListByKey(parkId);
        String infoPath = "/profile/gmParkRate";
        File dir = new File(Global.getDownloadPath()+parkId);
        if(!dir.exists()){
            dir.mkdirs();
        }
        if(fileUploadInfos!=null&&fileUploadInfos.size()>0){
            //执行循环将需要下载的文件拷贝到下载目录下
            for(FileUploadInfo fileUploadInfo:fileUploadInfos){
                String newPath = fileUploadInfo.getFilePath().replaceAll(infoPath,Global.getGmParkRatePath());
                File file = new File(newPath);
                File newFile = new File(dir + File.separator + fileUploadInfo.getFileName());
                try {
                    Files.copy(file.toPath(),newFile.toPath());
//                    fileUploadInfo.setFilePath(newFile.toPath().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }else{
            return AjaxResult.error("无附件！");
        }
        return AjaxResult.success("success",parkId);
    }

    /**
     * 将目录中的文件打包下载
     */
    @GetMapping("/downloadInfo")
    public void downloadInfo(String fileName, HttpServletRequest request, HttpServletResponse response) {
        try{
            ParkRate parkRate = gmParkRateService.selectGmParkRateById(fileName);
            String downloadName = parkRate.getUnitName() + "信息附件.zip";

            String sourceFilePath = Global.getDownloadPath() + fileName;
            String zipOutFilePath = Global.getDownloadPath() + downloadName;
            FileUtils.createZip(sourceFilePath,zipOutFilePath);
            try{
                response.setHeader("Content-Type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment; filename=" + FileUtils.setFileDownloadHeader(request,downloadName));
                FileUtils.writeBytes(zipOutFilePath,response.getOutputStream());
            }finally {
                try{
                    File zfile = new File(zipOutFilePath);
                    zfile.delete();
                    File sqlFile = new File(sourceFilePath);
                    FileUtils.deleteDir(sqlFile);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
